import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { tokenManager } from '../utils/token'
import { ElMessage } from 'element-plus'

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../page/logo.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/index',
    name: 'Index',
    component: () => import('../page/index_vice.vue'),
    meta: {
      title: '首页',
      requiresAuth: true
    }
  },
  {
    path: '/newIndex',
    name: 'newIndex',
    component: () => import('../page/index.vue'),
    meta: {
      title: '首页',
      requiresAuth: true
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta?.title) {
    document.title = `澳玛小红书投放评估工具`
  }
  
  // 检查是否需要登录
  if (to.meta?.requiresAuth) {
    // 检查token是否存在且未过期
    if (!tokenManager.hasToken()) {
      ElMessage.warning('请先登录')
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 保存原始路径，登录后可以跳转回来
      })
      return
    }
  }
  
  // 如果已登录用户访问登录页，重定向到首页
  if (to.path === '/login' && tokenManager.hasToken()) {
    next('/index')
    return
  }
  
  next()
})

// 路由错误处理
router.onError((error) => {
  console.error('路由错误:', error)
  ElMessage.error('页面加载失败')
})

export default router